package com.mocaris.android.gank.http

import com.google.gson.JsonElement
import com.mocaris.android.gank.api.GankIoAPI
import com.mocaris.android.gank.api.WanAndroidAPI
import com.mocaris.android.gank.constants.Constant
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit


/**
 * @Author mocaris
 * @Date 2019-06-17 17:03
 */
object HttpUtil {

    private val timeOut = 10000L

    private val okHttpClient: OkHttpClient = OkHttpClient.Builder()
        .connectTimeout(timeOut, TimeUnit.MILLISECONDS)
        .retryOnConnectionFailure(true)
        .addNetworkInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.HEADERS))
        .addNetworkInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
        .build()

    private val retrofit: Retrofit.Builder = Retrofit.Builder()
        .client(okHttpClient)
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())

    private val wanAndroid: WanAndroidAPI = retrofit
        .baseUrl(Constant.BASE_URL_WAN_ANDROID)
        .build().create(WanAndroidAPI::class.java)

    private val gankIo: GankIoAPI = retrofit
        .baseUrl(Constant.BASE_URL_GANK_IO)
        .build().create(GankIoAPI::class.java)

    fun requestWanAndroid(): WanAndroidAPI {
        return wanAndroid
    }

    fun requestGankIo(): GankIoAPI {
        return gankIo
    }

}

/**
 * 拦截wanandroid 数据
 */
fun Observable<WanAndroidResponseBody>.acceptWanAndroidResponse(): Observable<JsonElement> {
    return this.flatMap {
        val errmsg = it.errorMsg
        val errCode = it.errorCode
        when (errCode) {
            0 -> {
                val jsonElement = it.data!!
                Observable.just(jsonElement)
            }
            else -> {
                Observable.error<JsonElement>(HttpResException(errCode, errmsg))
            }
        }
    }.compose {
        it.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
    }
}

/**
 * 拦截gankio 返回数据
 */
fun Observable<GankIoResponseBody>.acceptGankIoResponse(): Observable<JsonElement> {
    return this.flatMap {
        val error = it.error
        if (!error) {
            val jsonElement = it.results!!
            Observable.just(jsonElement)
        } else {
            Observable.error<JsonElement>(HttpResException(-1, "错误"))
        }
    }.compose {
        it.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
    }
}